package com.renren.http.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.renren.http.Base;
import com.renren.http.beans.User;
import com.renren.http.utils.PageUtils;
import com.renren.http.utils.parser.ParserUtils;

@SuppressWarnings("deprecation")
public class RenRen extends Base implements RenRenInterface{
	
	private HttpClient httpclient;
	
	private String username;
	private String password;
	private String id;
	private String sid;
	private Integer numberFriends;
	private Integer numberPage;
	private List<User> users;
	
	private String Success_URL;
	  
	private static final String DETAIL_URL = "http://3g.renren.com/details.do";
	private static final String LOGIN_URL = "http://3g.renren.com/login.do";
	private static final String FERIND_LIST_URL = "http://3g.renren.com/friendlist.do";
	
	private static final String uString = "email";
	private static final String pString = "password";
	
	/** 每页最多4个好友**/
	public static final int PAGE_SIZE_FRIENDS = 4;
	
	public RenRen(){
		httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
		users = new ArrayList<User>();
		INFO("初始化人人客户端"+httpclient.toString());
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		RenRen renren = new RenRen();
		
		renren.login("chenshi5012@163.com", "1qaz2wsx");
		
//		renren.getUserInfo();
//		renren.getFriendCount();
//		renren.getFriendList();
		
		User u = new User();
		u.setId(225759382);
		renren.getFriendDetail(u);
		//renren.getFriendsDetail();
		
	}

	public void login(String username, String password) {
		this.username = username;
		this.password = password;
		login();
	}

	public void login() {
		
		INFO("登录参数 用户名【"+username+"】,密码:【"+password+"】");
		List <NameValuePair> nvps = getKey();
		nvps.add(new BasicNameValuePair(uString,username));
		nvps.add(new BasicNameValuePair(pString,password));
		
		HttpPost httpost = new HttpPost("http://3g.renren.com/login.do?autoLogin=true&&fx=0");
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        
		try {
			httpost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
			INFO("------------------登             录---------------------");
			HttpResponse response = httpclient.execute(httpost);
			INFO("------------------登录串获取---------------------");
			HttpEntity entity = response.getEntity();
			InputStream content = entity.getContent();
			String successContent = PageUtils.pipe(content, null);
			EntityUtils.consume(entity);
			setSuccess_URL(successContent);
			INFO("------------------进 入   首 页---------------------");
			HttpGet httpget = new HttpGet(Success_URL);
			httpclient.execute(httpget);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void logout() {
		// TODO Auto-generated method stub
		
	}

	public void getPage(String url) {
		// TODO Auto-generated method stub
		
	}
	
	
	
	/**
	 *  
	 *  取得form表单中的隐藏值
	 *  
	 * 
	 */
	public List <NameValuePair> getKey(){
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		try {
			String content = PageUtils.getContent(httpclient, LOGIN_URL+"?email="+username);
			nvps =  Parser(content);
		} catch (Exception e) {
			INFO(e);
			e.printStackTrace();
		}
		return nvps;
	}
	
	
	/**
	 *  
	 *  解析 -隐藏参数
	 *  
	 * 
	 */
	private List <NameValuePair> Parser(String content){
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		
		Document doc = Jsoup.parse(content);
		
		Element form = doc.select("form").first();
		Elements namevalue = form.getElementsByAttribute("name");
		for(Element e:namevalue){
			if(!(e.attr("name").equals(uString) || e.attr("name").equals(pString))){
				NameValuePair nvp = new BasicNameValuePair(e.attr("name"),e.attr("value"));
				nvps.add(nvp);
			}
		}
		
		return nvps;
	}
	
	/**
	 *  
	 *  解析 -成功URL
	 *  
	 * 
	 */
	private void setSuccess_URL(String s) throws Exception{
		Document doc = Jsoup.parse(s);
		Element herf = doc.select("a").first();
		Success_URL  = herf.attr("href");
		try{
			String params = Success_URL.substring(Success_URL.indexOf('?')+1,Success_URL.length());
			
			String[] nvps = params.split("&");
			String[]  sids = nvps[0].split("=");
			sid = sids[1];
			
			String[] nvp = nvps[1].split("=");
			String[] con = nvp[1].split("_");
			id = con[0];
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	public User getUserInfo() {
		INFO("------------------获取用户信息---------------------");
		try{
			INFO(PageUtils.getContent(httpclient,DETAIL_URL+"?id="+id));
		}catch(Exception e){
			INFO(e);
		}
        return null;
	}
	
	public List<User> getFriendList() {
		INFO("------------------获取用户列表---------------------");
		if(numberPage == 0){
			numberPage = getFriendPage();
		}
		
		
		for(int id = 0;id<numberPage;id++){
			try{
				String content = PageUtils.getContent(httpclient,FERIND_LIST_URL+"?curpage="+id);
				List<Integer> ids = ParserUtils.parserFriendId(content);
				
				for(Integer d:ids){
					User user = new User();
					user.setId(d);
					users.add(user);
				}
				
			}catch(Exception e){
				INFO(e);
			}
		}
		
		return users;
	}
	
	public int getFriendCount(){
		INFO("------------------获取用户数量---------------------");
		try {
			String tmp = PageUtils.getContent(httpclient, FERIND_LIST_URL
					+ "?curpage=999999");
			numberFriends = ParserUtils.parserFriendCount(tmp);
			numberPage = ParserUtils.parserFriendPage(tmp);
		} catch (Exception e) {
			INFO(e);
		}
		return numberFriends;
	}
	
	
	public int getFriendPage(){
		INFO("------------------获取好友页数---------------------");
		try {
			String tmp = PageUtils.getContent(httpclient, FERIND_LIST_URL
					+ "?curpage=999999");
			numberFriends = ParserUtils.parserFriendCount(tmp);
			
		} catch (Exception e) {
			INFO(e);
		}
		return numberFriends;
	}
	
	
	public void getFriendsDetail(){
		INFO("------------------获取所有好友详细---------------------");
		for(User user: users){
			getFriendDetail(user);
			System.out.println(user);
		}
			
	}
	
	public void getFriendDetail( User user){
		INFO("------------------获取【"+user.getId()+"】详细---------------------");
		try {
			String tmp = PageUtils.getContent(httpclient, DETAIL_URL
					+ "?id="+user.getId());
			ParserUtils.parserUser(tmp,user);
			INFO(user.getMsg());
		} catch (Exception e) {
			INFO(e);
		}
			
	}
	
	
	
	public List<User> getUsers() {
		return users;
	}

	public String getId() {
		return id;
	}
	
	public String getSid() {
		return sid;
	}
}
